// @decoratorTaskQueue({ maxLen: 10 })
export class Example {
  constructor(TaskQueue) {
    const taskQueue = new TaskQueue({ maxLen: 10 });
    taskQueue.push(...task).then((res) => {
      console.log(res);
    });
    taskQueue.push(...task2).then((res) => {
      console.log(res);
    });
    taskQueue.on("task3", console.log).push(...task3);
    taskQueue.push(...task4).then((res) => {
      console.log(res);
    });
    taskQueue.on(taskQueue.defaultKey, console.log).push(...task5);
    taskQueue.push(...task6).then((res) => {
      console.log(res);
    });
    const fn = (params) => params;
    taskQueue.push([fn.bind(this, "hello")], "task1");
    taskQueue.push([fn.bind(this, "world")], "task1").then(console.log); // [ 'hello', 'world' ]
    taskQueue.push([fn.bind(this, "world")], "task2").then(console.log); // [ 'world' ]
    taskQueue.on(taskQueue.defaultKey, console.log).push([() => {}]);
    const stopFn = async () => {
      const stopQueue = new TaskQueue({
        maxLen: 1,
        stepCb: (data) => {
          console.log(data);
        },
      });
      const key = "key1";
      const queue = [
        () => Promise.resolve("hello"),
        () => Promise.resolve("1"),
        () => Promise.resolve("stop"),
        () => Promise.resolve("2"),
        () => Promise.reject("3"),
      ];
      stopQueue.push(queue, "key1");
      for (let i = 1; i < queue.length + 1; i++) {
        stopQueue.on(key + `:${i}`, (data) => {
          const isStop = data.step === 3;
          console.log(isStop);
          if (isStop) stopQueue.clearQueue();
        });
      }
    };
    stopFn();
  }
}

const syncFn = (args) => {
  return new Promise((resolve, reject) => {
    if (args.includes("error")) {
      return setTimeout(reject.bind(null, args), 100);
    }
    return setTimeout(resolve.bind(null, args), 100);
  });
};

const createFnList = (length, name) => {
  const task = [[], name];
  while (length--) {
    const params = `${name ?? "default"}:${
      length % 3 === 1 ? "error" + length : "params" + length
    }`;
    task[0].push(syncFn.bind(null, params));
  }
  return task;
};

const task = createFnList(10, "task1");
const task2 = createFnList(24, "task2");
const task3 = createFnList(8, "task3");
const task4 = createFnList(55, "task4");
const task5 = createFnList(10);
const task6 = createFnList(22);
if (typeof define === "function" && define.amd) {
  // amd环境
  define(Example);
} else if (typeof exports === "object") {
  // cmd环境
  exports.Example = Example;
} else if (typeof Window === "object") {
  // 浏览器环境下
  window.Example = Example;
}
